package com.example.demo.service;

import com.alibaba.fastjson.JSON;
import com.example.demo.pojo.Content;
import com.example.demo.util.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: huanggaotao
 * @Description:
 * @Date: Created in 15:01 2021/7/29
 * @Modified By:
 */
//业务编写
@Service
public class ContentService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //1、网上爬取数据放入es索引中
    public Boolean parseContent(String keywords) throws IOException {
        //爬取出来的数据
        List<Content> contents = new HtmlParseUtil().parseJD(keywords);

        //把查询到的数据放入es
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i = 0; i < contents.size(); i++) {
            System.out.println(JSON.toJSONString(contents.get(i)));
            bulkRequest.add(
                    new IndexRequest("hgt")
                        .source(JSON.toJSONString(contents.get(i)), XContentType.JSON)
            );
        }
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            return !bulk.hasFailures();
        }


        //2、从elasticSearch中获取这些数据实现搜索功能
        public List<Map<String, Object>> searchPage(String keyword,int pageNum,int pageSize) throws IOException {
            if (pageNum<=1) {
                pageNum = 1;
            }
            //条件搜索
            SearchRequest searchRequest = new SearchRequest("hgt");
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            //分页
            searchSourceBuilder.from(pageNum);
            searchSourceBuilder.size(pageSize);

            //精准匹配
            TermQueryBuilder title = QueryBuilders.termQuery("title", keyword);
            searchSourceBuilder.query(title);
            searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

            //高亮
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("title");
            highlightBuilder.preTags("<span style='color:red'>");
            highlightBuilder.postTags("</span>");
            //关闭多个高亮功能  就比如 在一个商品的一个title中，只需要高亮一个vue关键字就好
            highlightBuilder.requireFieldMatch(false);
            searchSourceBuilder.highlighter(highlightBuilder);


            //执行搜索
            searchRequest.source(searchSourceBuilder);
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            //解析结果
            List<Map<String, Object>> list = new ArrayList<>();
            for (SearchHit hit : searchResponse.getHits()) {

                //解析高亮的字段
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();

                HighlightField title1 = highlightFields.get("title");
                //原来的结果
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                //解析高亮的字段
                if (title1!=null) {
                    Text[] fragments = title1.fragments();
                    //把高亮的字段 替换掉原来没有高亮的字段
                    String newTitle = "";
                    for (Text fragment : fragments) {
                        newTitle += fragment;
                    }
                    sourceAsMap.put("title",newTitle);
                }

                list.add(hit.getSourceAsMap());
            }
            return list;
    }

    //2、从elasticSearch中获取这些数据实现搜索功能   高亮版本
    public List<Map<String, Object>> searchHighlightPage(String keyword,int pageNum,int pageSize) throws IOException {
        if (pageNum<=1) {
            pageNum = 1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("hgt");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //分页
        searchSourceBuilder.from(pageNum);
        searchSourceBuilder.size(pageSize);

        //精准匹配
        TermQueryBuilder title = QueryBuilders.termQuery("title", keyword);
        searchSourceBuilder.query(title);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        //关闭多个高亮功能  就比如 在一个商品的一个title中，只需要高亮一个vue关键字就好
        highlightBuilder.requireFieldMatch(false);
        searchSourceBuilder.highlighter(highlightBuilder);


        //执行搜索
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //解析结果
        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits()) {

            //解析高亮的字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();

            HighlightField title1 = highlightFields.get("title");
            //原来的结果
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            //解析高亮的字段
            if (title1!=null) {
                Text[] fragments = title1.fragments();
                //把高亮的字段 替换掉原来没有高亮的字段
                String newTitle = "";
                for (Text fragment : fragments) {
                    newTitle += fragment;
                }
                sourceAsMap.put("title",newTitle);
            }

            list.add(hit.getSourceAsMap());
        }
        return list;
    }



    }
